package com.zjlanyun.eplus;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.aihook.progressview.library.ProgressViewDialog;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.KeyboardUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.snappydb.DB;
import com.snappydb.DBFactory;
import com.snappydb.SnappydbException;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.greendao.DBHelper;
import com.zjlanyun.eplus.greendao.IrActWindow;
import com.zjlanyun.eplus.greendao.IrChoiceBill;
import com.zjlanyun.eplus.greendao.IrModel;
import com.zjlanyun.eplus.greendao.IrModelFields;
import com.zjlanyun.eplus.greendao.IrSearchFields;
import com.zjlanyun.eplus.greendao.IrUiMenu;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.SPData;
import com.zjlanyun.eplus.utils.Toastor;
import com.zjlanyun.eplus.view.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ConnectSetup extends BaseActivity {

    private String serverUrl;
    private ProgressViewDialog mProgressViewDialog;
    @Bind(R.id.btn_save) Button btn_save;
    @Bind(R.id.et_server_url) EditText et_server_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect_setup);
        initBaseView();
        initView();
    }

    private void initView() {
        if (!SPData.getUserinfo().getString("serverUrl", "").equals("")) {
            et_server_url.setText(SPData.getUserinfo().getString("serverUrl", ""));
        }

        title.setText("连接设置");

        //保存
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View arg0) {
                serverUrl = et_server_url.getText().toString();
                if (TextUtils.isEmpty(serverUrl)) {
                    ToastUtils.showShortToast("请输入业务系统地址");
                } else {
                    mProgressViewDialog = new ProgressViewDialog(mContext);
                    mProgressViewDialog.showWithMaskType(ProgressViewDialog.ProgressViewDialogMaskType.None);
                    SPData.getUserinfo().putString("serverUrl", serverUrl);
                    HttpRequest client = new HttpRequest(mContext, WebApi.api(), false);
                    client.getRequest().add("action", "connectConfig");
                    client.send(new SimpleHttpListener<JSONObject>() {
                        @Override
                        public void onSucceed(int what, final Response<JSONObject> response) {
                            super.onSucceed(what, response);
                            Observable.create(new Observable.OnSubscribe<String>() {
                                @Override
                                public void call(Subscriber<? super String> subscriber) {
                                    updateSetting(response.get(), mContext);
                                    subscriber.onCompleted();
                                }
                            }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {
                                    ToastUtils.showShortToast("保存成功");
                                    KeyboardUtils.hideSoftInput(mActivity);
                                    mProgressViewDialog.dismiss();
                                    // 判断用户是否已经登录
                                    if (SPData.getUserinfo().getBoolean("isLogin", false)) {
                                        finish();
                                    } else {
                                        if (getIntent().getStringExtra("from") != null) {
                                            if (getIntent().getStringExtra("from").equals(Login.class.getName())) {
                                                finish();
                                            }
                                        } else {
                                            Intent intent = new Intent(mContext, Login.class);
                                            startActivity(intent);
                                            finish();
                                        }
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {

                                }
                            });
                        }

                        @Override
                        public void onFailed(int what, Response<JSONObject> response) {
                            super.onFailed(what, response);
                            mProgressViewDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    /**
     * 更新配置
     *
     * @param jsonObject
     */
    public void updateSetting(JSONObject jsonObject, Context context) {
        try {
            DBHelper.getDaoSession(context).getIrUiMenuDao().deleteAll();
            JSONArray ir_ui_menu = jsonObject.getJSONObject("data").getJSONArray("ir_ui_menu");
            ArrayList<IrUiMenu> ir_ui_menuList = new ArrayList<>(JSON.parseArray(ir_ui_menu.toString(), IrUiMenu.class));
            for (int i = 0; i < ir_ui_menuList.size(); i++) {
                DBHelper.getDaoSession(context).getIrUiMenuDao().insertOrReplace(ir_ui_menuList.get(i));
            }

            DBHelper.getDaoSession(context).getIrActWindowDao().deleteAll();
            JSONArray ir_act_window = jsonObject.getJSONObject("data").getJSONArray("ir_act_window");
            ArrayList<IrActWindow> ir_act_windowList = new ArrayList<>(JSON.parseArray(ir_act_window.toString(), IrActWindow.class));
            for (int i = 0; i < ir_act_windowList.size(); i++) {
                DBHelper.getDaoSession(context).getIrActWindowDao().insertOrReplace(ir_act_windowList.get(i));
            }

            DBHelper.getDaoSession(context).getIrModelFieldsDao().deleteAll();
            JSONArray ir_model_fields = jsonObject.getJSONObject("data").getJSONArray("ir_model_fields");
            ArrayList<IrModelFields> ir_model_fieldsList = new ArrayList<>(JSON.parseArray(ir_model_fields.toString(), IrModelFields.class));
            for (int i = 0; i < ir_model_fieldsList.size(); i++) {
                DBHelper.getDaoSession(context).getIrModelFieldsDao().insertOrReplace(ir_model_fieldsList.get(i));
            }

            DBHelper.getDaoSession(context).getIrModelDao().deleteAll();
            JSONArray ir_model = jsonObject.getJSONObject("data").getJSONArray("ir_model");
            ArrayList<IrModel> irModelArrayList = new ArrayList<>(JSON.parseArray(ir_model.toString(), IrModel.class));
            for (int i = 0; i < irModelArrayList.size(); i++) {
                DBHelper.getDaoSession(context).getIrModelDao().insertOrReplace(irModelArrayList.get(i));
            }

            DBHelper.getDaoSession(context).getIrSearchFieldsDao().deleteAll();
            JSONArray ir_search_fields = jsonObject.getJSONObject("data").getJSONArray("ir_search_fields");
            ArrayList<IrSearchFields> irSearchFieldsArrayList = new ArrayList<>(JSON.parseArray(ir_search_fields.toString(), IrSearchFields.class));
            for (int i = 0; i < irSearchFieldsArrayList.size(); i++) {
                DBHelper.getDaoSession(context).getIrSearchFieldsDao().insertOrReplace(irSearchFieldsArrayList.get(i));
            }

            DBHelper.getDaoSession(context).getIrChoiceBillDao().deleteAll();
            JSONArray ir_choice_bill = jsonObject.getJSONObject("data").getJSONArray("ir_choice_bill");
            ArrayList<IrChoiceBill> irChoiceBillArrayList = new ArrayList<>(JSON.parseArray(ir_choice_bill.toString(), IrChoiceBill.class));
            for (int i = 0; i < irChoiceBillArrayList.size(); i++) {
                DBHelper.getDaoSession(context).getIrChoiceBillDao().insertOrReplace(irChoiceBillArrayList.get(i));
            }

            SPData.getConfig().putString("device_bind_url", jsonObject.getJSONObject("data").getString("device_bind_url"));
            SPData.getConfig().putString("device_unbind_url", jsonObject.getJSONObject("data").getString("device_unbind_url"));
            SPData.getConfig().putString("device_logout_url", jsonObject.getJSONObject("data").getString("device_logout_url"));
            SPData.getConfig().putString("update_url", jsonObject.getJSONObject("data").getString("update_url"));

            try {
                DB snappydb = DBFactory.open(context);
                snappydb.destroy();
            } catch (SnappydbException e) {
                e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toastor.getInstance().showShortToast("配置参数获取出错");
            return;
        }
    }
}
